//
//  DragScrollView.m
//  TableViewDrag
//
//  Created by max on 2018/10/30.
//  Copyright © 2018年 max. All rights reserved.
//

#import "DragScrollView.h"
#import "DragTableView.h"

@interface DragScrollView ()<UIScrollViewDelegate>

@property (nonatomic, strong) UIView *snapshot;
@property (nonatomic, strong) NSIndexPath *fromIndexPath;
@property (nonatomic, assign) int index;
@property (nonatomic, assign) BOOL didDrag;
@property (nonatomic, strong) NSString *dataSource;

@end

@implementation DragScrollView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.pagingEnabled = true;
        self.clipsToBounds = false;
        self.delegate = self;
        [self addGesture];
        self.didDrag = false;
        self.index = 0;
    }
    return self;
}


- (void)addGesture {
    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(processGesture:)];
    longPressGesture.minimumPressDuration = 1.0;
    [self addGestureRecognizer:longPressGesture];
}


- (void)processGesture:(UILongPressGestureRecognizer *)gesture {
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan: {
            [self gestureBegan:gesture];
        }
            break;
        case UIGestureRecognizerStateChanged: {
            [self gestureChanged:gesture];
        }
            break;
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateCancelled: {
            [self gestureEndedOrCancelled:gesture];
        }
            break;
        default: break;
    }
}

- (void)gestureBegan:(UILongPressGestureRecognizer *)gesture {
    self.didDrag = true;
    CGPoint point = [gesture locationInView:gesture.view];
    int selectIndex = point.x / self.frame.size.width;
    DragTableView *selectTableView = self.contentViews[selectIndex];
    NSIndexPath *fromIndexPath = [selectTableView indexPathForRowAtPoint:[self convertPoint:point toView:selectTableView]];
    
    UITableViewCell *cell = [selectTableView selectCellAtIndexPath:fromIndexPath];
    
    self.snapshot = [cell snapshotViewAfterScreenUpdates:NO];
//    self.snapshot = [self snapshotViewWithInputView:cell];
    self.snapshot.frame = [selectTableView convertRect:cell.frame toView:self];
    cell.hidden = true;
    [self addSubview:self.snapshot];
    [UIView animateWithDuration:0.25 animations:^{
        self.snapshot.transform = CGAffineTransformMakeScale(1.05, 1.05);
        self.snapshot.center = point;
    }];
    
    self.fromIndexPath = fromIndexPath;
    
    self.dataSource = selectTableView.dataArray[fromIndexPath.row];
}


- (void)gestureChanged:(UILongPressGestureRecognizer *)gesture {
    CGPoint point = [gesture locationInView:gesture.view];
    self.snapshot.center = point;
    int tempIndex = point.x / self.frame.size.width;
    if (self.index != tempIndex && tempIndex < self.contentViews.count) {
        
        DragTableView *fromTableView = (DragTableView *)self.contentViews[self.index];
        
        [fromTableView.dataArray removeObjectAtIndex:self.fromIndexPath.row];
        [fromTableView deleteRowsAtIndexPaths:@[self.fromIndexPath] withRowAnimation:UITableViewRowAnimationNone];
        
        [self setContentOffset:CGPointMake(self.frame.size.width * tempIndex, 0) animated:true];
        DragTableView *tempTableView = (DragTableView *)self.contentViews[tempIndex];
        CGPoint tempPoint = [self convertPoint:point toView:tempTableView];
        tempPoint.x = 0;
        NSIndexPath *toIndexPath = [tempTableView indexPathForRowAtPoint:tempPoint];
        if (!toIndexPath) {
            toIndexPath = [NSIndexPath indexPathForRow:tempTableView.dataArray.count inSection:0];
        }
        [tempTableView.dataArray insertObject:self.dataSource atIndex:toIndexPath.row];
        tempTableView.dataArray = tempTableView.dataArray;
        self.index = tempIndex;
        self.fromIndexPath = toIndexPath;
    }else {
        DragTableView *selectTableView = self.contentViews[self.index];
        NSIndexPath *toIndexPath = [selectTableView indexPathForRowAtPoint:[self convertPoint:point toView:selectTableView]];
        if (!toIndexPath) {
            return;
        }
        [selectTableView.dataArray exchangeObjectAtIndex:self.fromIndexPath.row withObjectAtIndex:toIndexPath.row];
        [selectTableView moveRowAtIndexPath:self.fromIndexPath toIndexPath:toIndexPath];
        self.fromIndexPath = toIndexPath;
    }
}

- (void)gestureEndedOrCancelled:(UILongPressGestureRecognizer *)gesture {
    self.didDrag = false;
    DragTableView *selectTableView = self.contentViews[self.index];
    UITableViewCell *cell = [selectTableView cellForRowAtIndexPath:self.fromIndexPath];
    [UIView animateWithDuration:0.25 animations:^{
        self.snapshot.transform = CGAffineTransformIdentity;
        self.snapshot.frame = [selectTableView convertRect:cell.frame toView:self];
    } completion:^(BOOL finished) {
        cell.hidden = NO;
        [self.snapshot removeFromSuperview];
        self.snapshot = nil;
    }];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (!self.didDrag) {
        self.index = scrollView.contentOffset.x / scrollView.frame.size.width;
    }
}

- (UIView *)snapshotViewWithInputView:(UIView *)inputView {
    UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, NO, 0);
    [inputView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageView *snapshot = [[UIImageView alloc] initWithImage:image];
    return snapshot;
}

- (NSMutableArray *)contentViews {
    if (!_contentViews) {
        _contentViews = @[].mutableCopy;
    }
    return _contentViews;
}

@end
